<?php

class Database
{
	protected $_connection;
	
	public function __construct()
	{
		$this->connect();
	}
	
	public function connect()
	{
		$dsn = 'mysql:dbname=' . APP_DB_NAME . ';host=' . APP_DB_HOST;
		
		$this -> _connection = new PDO(
				$dsn,
				APP_DB_USER,
				APP_DB_PASSWORD
		);
	
		$this -> _connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
	
	public function getConnection()
	{
		return $this -> _connection;
	}
	
	public function execute($query, $params = array())
	{
		try{
			$stmt = $this -> _connection->prepare($query);
			$stmt->execute($params);
			
			return $stmt;
		}
		catch(Exception $ex)
		{
			if(DEBUG)
				echo "Errors: " . $ex;
			
			return null;
		}
	}
	
	# Trả về 1 text
	public function executeScalar($sql,$params = array())
	{
		$result = $this->execute($sql, $params)->fetch(PDO::FETCH_UNIQUE);
		
		if($result != null)
			return $result[0];
		else
			return null;
	}
	
	# Trả về 1 record (array)
	public function executeRow($sql,$params = array())
	{
		return $this->execute($sql, $params)->fetch(PDO::FETCH_ASSOC);
	}
	
	# Trả về mảng các record
	public function executeAll($query, $params=array(), $isPaging=true)
	{
		try{
			if($isPaging)
			{
				$start = 0;
				$limit = RECORDS_PER_PAGE;
		
				if(isset($_GET['start']))
				{
					$start = $_GET['start'] + 0;
				}
		
				if(isset($_GET['limit']))
				{
					$limit = $_GET['limit'] + 0;
				}
		
				$query .= " LIMIT $start, $limit";
			}
			
			$result = $this -> execute($query, $params)->fetchAll(PDO::FETCH_ASSOC); 
			
			return $result;
		}
		catch(Exception $ex)
		{
			if(DEBUG)
				echo "Errors: " . $ex;
			
			return null;
		}
	}
	
	# Trả về mảng các record và tổng số record
	public function executeAllTotal($query, $params=array(), $isPaging=true)
	{
		if($isPaging)
		{
			$start = 0;
			$limit = RECORDS_PER_PAGE;
	
			if(!stristr($query, 'sql_calc_found_rows'))
			{
				$temp = preg_split('/^\w*/', $query);
				$query = "SELECT sql_calc_found_rows " . $temp[1];
			}
	
			if(isset($_GET['start']))
			{
				$start = $_GET['start'] + 0;
			}
	
			if(isset($_GET['limit']))
			{
				$limit = $_GET['limit'] + 0;
			}
	
			$query .= " LIMIT $start, $limit";
		}
		
		$result = $this -> execute($query, $params)->fetchAll(PDO::FETCH_ASSOC);
		
		$query = "SELECT found_rows()";
		
		$total = $this->execute($query)->fetch(PDO::FETCH_UNIQUE);
		$total = $total[0];
		
		return array($result, $total);
	}
	
	# Thực hiện update, delete
	public function executeNone($query, $params = array())
	{
		return $this->execute($query, $params)->execute();
	}
}